import { createAsyncThunk, createSlice, type PayloadAction } from "@reduxjs/toolkit";
import * as API from '../api/http'
import type{listTS} from './listTS'
type initialStateTS={
    list:Array<listTS>
}
const initialState:initialStateTS={
    list:[]
}
const crmsSlice = createSlice({
    name: "crms",
    initialState,
    reducers: {
        r_getlist(state:initialStateTS,action:PayloadAction<Array<listTS>>){
            state.list=action.payload
        },
        r_addlist(state:initialStateTS,action:PayloadAction<listTS>){
            state.list.push(action.payload)
        },
        r_editlist(state:initialStateTS,action:PayloadAction<listTS>){
            let i=state.list.findIndex(item=>{
                return item.id==action.payload.id
            })
            state.list[i]=action.payload
        },
        r_dellist(state:initialStateTS,action:PayloadAction<number|string>){
            state.list=state.list.filter(item=>{
                return item.id!==action.payload
            })
        },
    },
});

export const actionfn = crmsSlice.actions;
export default crmsSlice.reducer;
export let async_getlist=createAsyncThunk('async_getlist',async(_,store)=>{
    let res= await API.getlist()
    store.dispatch(actionfn.r_getlist(res))
})
export let async_addlist=createAsyncThunk('async_addlist',async(obj:listTS,store)=>{
    let res= await API.addlist(obj)
    store.dispatch(actionfn.r_addlist(res))
})
export let async_editlist=createAsyncThunk('async_editlist',async(obj:listTS,store)=>{
    let res= await API.editlist(obj)
    store.dispatch(actionfn.r_editlist(res))
})
export let async_dellist=createAsyncThunk('async_dellist',async(id:number|string,store)=>{
    await API.dellist(id)
    store.dispatch(actionfn.r_dellist(id))
})
// export let async_searchcode=createAsyncThunk('async_searchcode',async(title:number,store)=>{
//     let res= await API.searchcode(title)
//     store.dispatch(actionfn.r_getlist(res as any))
// })
// export let async_searchtitle=createAsyncThunk('async_searchtitle',async(keyname:string,store)=>{
//     let res= await API.searchname(keyname)
//     store.dispatch(actionfn.r_getlist(res as any))
// })
// export let async_searchstat=createAsyncThunk('async_searchstat',async(state:boolean,store)=>{
//     let res= await API.searchstate(state)
//     store.dispatch(actionfn.r_getlist(res as any))
// })